<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/9 0009
 * Time: 下午 2:53
 */
namespace app\admin\controller;
use app\common\service\MiniProgramHelp;
use app\admin\model\Tenant;
use app\admin\model\Miniprogramtemplate;
use app\common\DictConstant;
use app\common\validate\Miniprogramtemplate as ValidateMiniprogramtemplate;
use app\common\validate\DraftsIdInt;
use app\common\validate\TemplateIdInt;
use app\common\validate\TenantConfig;
use app\common\validate\WechatAuth;
use think\Db;
use think\Request;

class MiniProgram extends Base {
    public function index(){

        $businessId = session('TENANT_ID');
        //获取小程序信息
        $data['businessMiniProgram'] = Tenant::get($businessId);

        //获取授权方的帐号基本信息
        $data['authorizerInfo'] = MiniProgramHelp::getAuthorizerInfo($businessId);
//        dump($data['authorizerInfo']);exit;
        if (!empty($data['authorizerInfo']['authorization_info'])) {
            //更新小程序二维码
            if ($data['authorizerInfo']['authorizer_info']['qrcode_url']) {
                $data['businessMiniProgram']->qrcodeUrl = $data['authorizerInfo']['authorizer_info']['qrcode_url'];
                $data['businessMiniProgram']->save();
            }

            //更新authorizerRefreshToken、authorizerAccessToken、authorizerAccessTokenExpires
            if ($data['authorizerInfo']['authorization_info']['authorizer_refresh_token'] != $data['businessMiniProgram']->authorizerRefreshToken) {
                $data['businessMiniProgram']->authorizerRefreshToken = $data['authorizerInfo']['authorization_info']['authorizer_refresh_token'];
                if ($data['businessMiniProgram']->save()) {
                    MiniProgramHelp::getAuthorizerToken($businessId, true);
                }
            }
        }

        //查询小程序模板
//        if (!empty($data['businessMiniProgram']->templateId)) {
//            $MiniprogramtemplateModel = new Miniprogramtemplate();
//            $data['template'] = $MiniprogramtemplateModel->where(['id' => $data['businessMiniProgram']->templateId, 'status' => 10])->find();
//        }

        //小程序审核版本的审核状态
        if (!empty($data['businessMiniProgram']) && $data['businessMiniProgram']->wxStatus == 2) {
            $businessMiniProgramStatus = MiniProgramHelp::getAuditStatus($businessId);

            //修改状态
            Tenant::updateStatusByAuditStatus($businessMiniProgramStatus, $data['businessMiniProgram']);

        }
        $qrcode = $this->showqrcode();
        if(isset($data['authorizerInfo']['errcode']) && isset($data['authorizerInfo']['errmsg'])){
            $data['authorizerInfo']['authorizer_info']['nick_name'] = '';
            $data['authorizerInfo']['authorizer_info']['principal_name'] = '';
        }

        $submissionaudit = Db::table('submissionaudit')->where('tenantId',$businessId)->whereTime('create_time','w')->select();
        $tijiaonums = count($submissionaudit);
        $this->assign('qrcode',$qrcode);
        $this->assign('data',$data);
        $this->assign('tenantId',$businessId);
        $this->assign('tijiaonums',$tijiaonums);
        $this->assign('shengyunums',(config('miniprogram.SubmissionNums') - $tijiaonums));
        return $this->fetch();
    }

    public function EditTenantConf(Request $request){
        $businessId = session('TENANT_ID');

        if($request->isAjax()){
            (new TenantConfig())->goCheck();
            $tenant = Tenant::get($businessId);
            $tenant->mchId = input('post.mchId');
            $tenant->mchKey = input('post.mchKey');
            if(input('post.certfile') && input('post.certkey')){
                $tenant->certfile = input('post.certfile');
                $tenant->certkey = input('post.certkey');
            }
            if($tenant->save() !== false){
                return json(['status' => 1, 'msg' => '修改成功']);
            }else{
                return json(['status' => 1, 'msg' => '修改失败']);
            }
        }
    }

    /**
     * 获取小程序体验二维码
     * @return \think\response\Json
     */
    public function showqrcode(){
        $businessId = session('TENANT_ID');
        $qrcodeurl = MiniProgramHelp::getQrcode($businessId);
        if($qrcodeurl){

            return $qrcodeurl;
        }else{
            return show(config('status.ERROR_STATUS'),"获取体验二维码失败",[]);
        }

    }

    /**
     * 跳转二维码授权页面
     * @author fei <xliang.fei@gmail.com>
     */
    public function AuthCode()
    {
        $businessId = session('TENANT_ID');
        $this->redirect(MiniProgramHelp::createAuthCode());
//        $storeModel = new \app\admin\model\Store();
//        $store = $storeModel->where('tenantId',$businessId)->find();
//        if($store){
//            $this->redirect(MiniProgramHelp::createAuthCode());
//        }else{
//            return $this->error('您还没有创建门店','/admin/store');
//        }


    }



    public function wechatauthlist(){
        return $this->fetch();
    }

    public function wechatauthcodecommit(){
        return $this->fetch();
    }

    /**
     * 上传小程序代码 不提交审核
     * @return mixed|\think\response\Json
     */
    public function commitCode(){
        if(request()->isPost()){
            $businessId = session('TENANT_ID');
            $postdata = input('post.');

            $validate = new WechatAuth();
            if(!$validate->check($postdata)){
                return show(config('status.ERROR_STATUS'),$validate->getError(),$postdata);
            }


            //修改服务器地址
            $result = MiniProgramHelp::modifyDomain(session('TENANT_ID'));

            if (isset($result['errcode']) && in_array($result['errcode'], [0, 85017])) {
                //提交代码
                $resultCommit = MiniProgramHelp::commitCode($businessId,$postdata['template_id'],$postdata['user_version'],$postdata['user_desc']);
                if ($resultCommit['errcode'] == 0){
                    return show(config('status.SUCCESS_STATUS'),"提交代码成功",'');
                }elseif ($resultCommit['errcode'] == 85014 || $resultCommit['errcode'] == 85043) {
                    return show(config('status.ERROR_STATUS'),"模板错误",$resultCommit['errmsg']);
                }


            } else {
                return show(config('status.ERROR_STATUS'),"提交代码失败",$result['errmsg']);
            }

        }else{
            return $this->fetch();
        }
    }

    public function alldemosubmissionaudit(){
        if(request()->isPost()){
            $postdata = input('post.');
            $validate = new WechatAuth();
            if(!$validate->check($postdata)){
                return show(config('status.ERROR_STATUS'),$validate->getError(),$postdata);
            }

            $Tenant = \app\common\model\Tenant::where('wxStatus',['=',10],['=',4],['=',3],'OR')->select();
            if($Tenant){
                $result = [];
                foreach ($Tenant as $v){
                    $res = $this->demosubmissionaudit($v['id'],$postdata);
                    array_push($result,$res);
                }
                return $result;
            }
            return ['status'=>0,'message'=>'没有可提交审核的商户'];

        }else{
            return $this->fetch();
        }

    }
    /**
     * 上传小程序代码提并交提交微信审核（添加）
     * @return array
     * @author fei <xliang.fei@gmail.com>
     */
    public function demosubmissionaudit($businessId,$postdata)
    {

            $businessMiniProgram = Tenant::get($businessId);
            //修改服务器地址
            $result = MiniProgramHelp::modifyDomain($businessId);
            if (isset($result['errcode']) && in_array($result['errcode'], [0, 85017])) {

                //提交代码
                $resultCommit = MiniProgramHelp::commitCode($businessId,$postdata['template_id'],$postdata['user_version'],$postdata['user_desc']);


                if ($resultCommit['errcode'] == 0) {
                    //提交审核
                    $resultSubmit = MiniProgramHelp::submitAuditCode($businessId,$postdata);
                    if (!empty($resultSubmit['errmsg']) && $resultSubmit['errmsg'] == 'ok') {
//                        $templateModel = new Miniprogramtemplate();
//                        $templateModel->businessId = $businessId;
//                        $templateModel->templateId = $postdata['template_id'];
//                        $templateModel->user_version = $postdata['user_version'];
//                        $templateModel->user_desc = $postdata['user_desc'];
//                        $templateModel->tag = $postdata['tag'];
//                        $templateModel->save();

                        $businessMiniProgram->auditid = $resultSubmit['auditid'];
                        $businessMiniProgram->version = $resultCommit['versions'];
                        $businessMiniProgram->templateId = $resultCommit['templateId'];
                        $businessMiniProgram->wxStatus = 2;
                        $businessMiniProgram->save();


                        return [
                            'status' => 1,
                            'message' => '提交审核成功',
                            'tenantName' => $businessMiniProgram->name
                        ];
                    } else {

                        if (!empty($resultSubmit['errcode']) && $resultSubmit['errcode'] == '85009') {

                            return [
                                'status' => 0,
                                'message' => '提交审核失败,已经有正在审核的版本',
                                'tenantName' => $businessMiniProgram->name
                            ];
                        }elseif ($resultSubmit['errcode'] == '85006'){
                            return [
                                'status' => 0,
                                'message' => '提交审核失败,小程序标签格式错误',
                                'tenantName' => $businessMiniProgram->name
                            ];
                        }

                        return [
                            'status' => 0,
                            'message' => '提交审核失败',
                            'tenantName' => $businessMiniProgram->name
                        ];
                    }
                } elseif ($resultCommit['errcode'] == 85014 || $resultCommit['errcode'] == 85043) {

                    return [
                        'status' => 0,
                        'message' => '提交审核失败,模板错误',
                        'tenantName' => $businessMiniProgram->name
                    ];
                    }

            } else {
                return [
                    'status' => 0,
                    'message' => '提交审核失败',
                    'tenantName' => $businessMiniProgram->name
                ];
            }



        //return json($data);
    }

    /**
     * 单个商户提交审核
     * @return mixed|\think\response\Json
     */
    public function onedemosubmissionaudit()
    {


        if(request()->isPost()){
            $businessId = session('TENANT_ID');
            //检查该商户提交的次数
            if(!$this->checkSubmissionNums($businessId)){
                return show(config('status.ERROR_STATUS'),'提交审核次数超过限制','提交审核次数超过限制');
            }
            $templateId = $this->newtemplateId();
            $postdata['template_id'] = $templateId['template_id'];
            $postdata['user_version'] = $templateId['user_version'];
            $postdata['user_desc'] = $templateId['user_desc'];
            $postdata['tag'] = $templateId['user_desc'];
            $validate = new WechatAuth();
            if(!$validate->check($postdata)){
                return show(config('status.ERROR_STATUS'),$validate->getError(),$postdata);
            }

            $businessMiniProgram = Tenant::get($businessId);

            //修改服务器地址
            $result = MiniProgramHelp::modifyDomain(session('TENANT_ID'));
            if (isset($result['errcode']) && in_array($result['errcode'], [0, 85017])) {

                //提交代码
                $resultCommit = MiniProgramHelp::commitCode($businessId,$postdata['template_id'],$postdata['user_version'],$postdata['user_desc']);

                if ($resultCommit['errcode'] == 0) {
                    //提交审核
                    $resultSubmit = MiniProgramHelp::submitAuditCode($businessId,$postdata);

                    if (!empty($resultSubmit['errmsg']) && $resultSubmit['errmsg'] == 'ok') {
//                        $templateModel = new Miniprogramtemplate();
//                        $templateModel->businessId = $businessId;
//                        $templateModel->templateId = $postdata['template_id'];
//                        $templateModel->user_version = $postdata['user_version'];
//                        $templateModel->user_desc = $postdata['user_desc'];
//                        $templateModel->tag = $postdata['tag'];
//                        $templateModel->save();

                        $businessMiniProgram->auditid = $resultSubmit['auditid'];
                        $businessMiniProgram->version = $resultCommit['versions'];
                        $businessMiniProgram->templateId = $resultCommit['templateId'];
                        $businessMiniProgram->wxStatus = 2;
                        $businessMiniProgram->save();
                        $data = [
                            'tenantId' => session('TENANT_ID'),
                            'create_time' => date('Y-m-d H:i:s',time())
                        ];
                        Db::table('submissionaudit')->insert($data);

                        return show(config('status.SUCCESS_STATUS'),"提交审核成功",$postdata);
                    } else {

                        if (!empty($resultSubmit['errcode']) && $resultSubmit['errcode'] == '85009') {
                            return show(config('status.ERROR_STATUS'),"提交审核失败,已经有正在审核的版本!",$resultSubmit['errmsg']);
                        }elseif ($resultSubmit['errcode'] == '85006'){
                            return show(config('status.ERROR_STATUS'),"小程序标签格式错误!",$resultSubmit['errmsg']);
                        }
                        return show($resultSubmit['errcode'],"提交审核失败01",$resultSubmit['errmsg']);
                    }
                } elseif ($resultCommit['errcode'] == 85014 || $resultCommit['errcode'] == 85043) {
                    return show(config('status.ERROR_STATUS'),"模板错误",$resultCommit['errmsg']);
                }

            } else {
                return show(config('status.ERROR_STATUS'),"提交审核失败02",'');
            }

        }else{
            return $this->fetch();
        }


        //return json($data);
    }

    private function checkSubmissionNums($businessId){
        $submissionaudit = Db::table('submissionaudit')->where('tenantId',$businessId)->whereTime('create_time','w')->select();
        if(count($submissionaudit) < config('miniprogram.SubmissionNums')){
            return true;
        }
        return false;
    }


    /**
     * 小程序模板
     * @param null $page
     * @return string
     */
    public function template($page = null)
    {
//        $data['page'] = $page;
//        $data['pageNum'] = Yii::$app->params['defaultPageSize'];
//        //设置默认请求页
//        if (empty($data['page'])) {
//            $data['page'] = 1;
//        }
//
//        $data['model'] = MiniProgramTemplate::find()
//            ->andWhere(['status' => 10])
//            ->orderBy('createTime DESC');
//
//        $data['total'] = $data['model']->count();
//        $data['pages'] = new Pagination(['totalCount' => $data['total'], 'pageSize' => $data['pageNum']]);
//        $data['model'] = $data['model']->offset(($data['page'] - 1) * $data['pageNum'])->limit($data['pages']->limit)->asArray()->all();
//
//        $data['industryList'] = Industry::find()->indexBy('id')->where(['status' => 10])->asArray()->all();
//
//        return $this->render('template', $data);
        return $this->fetch();
    }

    /**
     * 添加小程序模板

     * @return mixed|\think\response\Json
     */
    public function templateadd(){
        $businessid = session('TENANT_ID');
        if(empty($businessid)){
            return show(config('status.ERROR_STATUS'),"用户查询到商户信息，请登录");
        }
        if(request()->isPost()){
            $data = input('post.');
            $check = new ValidateMiniprogramtemplate();
            if(!$check->check($data)){
                return show(config('status.ERROR_STATUS'),$check->getError(),$data);
            }
            $file = request()->file('file-2');
            if($file){
                $info = $file->validate(config('upload.UPLOAD_RULE'))->move(config('path.Upload_path'));
                if($info){
                    $data['image'] = $info->getSaveName();
                }else{
                    return show(config('status.ERROR_STATUS'),$file->getError(),$data);
                }
            }else{
                unset($data['image']);
            }
            $data['businessId'] = $businessid;
            if(is_array($data)){
                $templateModel = new Miniprogramtemplate();
                $templateModel->data($data);
                $templateModel->allowField(true)->save();
                return show(config('status.SUCCESS_STATUS'),'ok',$data);
            }else{
                return show(config('status.ERROR_STATUS'),'非法数据',$data);
            }

        }else{
            return $this->fetch();
        }


    }

    /**
     * 获取第三方平台草稿箱
     * @return mixed
     */
    public function templatedrafts(){
        $businessId = session('TENANT_ID');
        $drafts = MiniProgramHelp::getTemplateDrafts($businessId);
        if($drafts['errcode'] == 0){
            $this->assign('drafts',$drafts['draft_list']);
        }elseif ($drafts['errcode'] == 85064){
            return show(config('status.ERROR_STATUS'),'找不到模版',$drafts['draft_list']);
        }else{
            return show(config('status.ERROR_STATUS'),'系统繁忙',$drafts['draft_list']);
        }

        return $this->fetch();

    }

    /**
     * 把草稿箱的模板添加到模板库
     * @return \think\response\Json
     */
    public function pushdraftstotemplate(){
        $businessId = session('TENANT_ID');
        $draft_id = input('get.');
        $validate = new DraftsIdInt();
        if(!$validate->check($draft_id)){
            return show(config('status.ERROR_STATUS'),$validate->getError(),$draft_id);
        }
        $res = MiniProgramHelp::pushDraftsToTemplate($businessId,$draft_id);
        if($res['errcode'] == 0){
            return show(config('status.SUCCESS_STATUS'),'ok',$draft_id);
        }elseif ($res['errcode'] == 85065){
            return show(config('status.ERROR_STATUS'),'模版库已满',$draft_id);
        }elseif ($res['errcode'] == 85064){
            return show(config('status.ERROR_STATUS'),'找不到草稿',$draft_id);
        }else{
            return show(config('status.ERROR_STATUS'),'系统繁忙',$draft_id);
        }
    }

    /**
     * 获取第三方平台模板库
     * @return mixed|\think\response\Json
     */
    public function templatelist(){
        $businessId = session('TENANT_ID');
        $templatelist = MiniProgramHelp::getTemplateList($businessId);
        if($templatelist['errcode'] == 0){
            $this->assign('templatelist',array_reverse($templatelist['template_list']));
        }elseif ($templatelist['errcode'] == 85064){
            return show(config('status.ERROR_STATUS'),'找不到模版',$templatelist['template_list']);
        }else{
            return show(config('status.ERROR_STATUS'),'系统繁忙',$templatelist['template_list']);
        }

        return $this->fetch();
    }

    /**
     * 获取最新的模板
     * @return \think\response\Json
     */
    public function newtemplateId(){
        $businessId = session('TENANT_ID');
        $templatelist = MiniProgramHelp::getTemplateList($businessId);
        if($templatelist['errcode'] == 0){
//            return show(config('status.SUCCESS_STATUS'),'ok',array_reverse($templatelist['template_list'])[0]);
            return array_reverse($templatelist['template_list'])[0];
        }elseif ($templatelist['errcode'] == 85064){
            return show(config('status.ERROR_STATUS'),'找不到模版',$templatelist['template_list']);
        }else{
            return show(config('status.ERROR_STATUS'),'系统繁忙',$templatelist['template_list']);
        }
    }

    /**
     * 删除模板
     * @return \think\response\Json
     */
    public function deltemplate(){
        $businessId = session('TENANT_ID');
        $template_id = input('get.');
        $validate = new TemplateIdInt();
        if(!$validate->check($template_id)){
            return show(config('status.ERROR_STATUS'),$validate->getError(),$template_id);
        }
        $res = MiniProgramHelp::DelTemplate($businessId,$template_id);
        if($res['errcode'] == 0){
            return show(config('status.SUCCESS_STATUS'),'ok',$template_id);
        }elseif ($res['errcode'] == 85064){
            return show(config('status.ERROR_STATUS'),'找不到模板',$template_id);
        }else{
            return show(config('status.ERROR_STATUS'),"系统繁忙",$res);
        }
    }

    /**
     * 获取体验者列表
     * @return mixed
     */
    public function getexperiencerlist(){
        $businessId = session('TENANT_ID');
        $res = MiniProgramHelp::GetExperiencerList($businessId);
        if($res['errcode'] == 0){
            dump($res);
        }
        return $this->fetch();
    }

    public function wechatjiebang(){
        $businessId = session('TENANT_ID');
        $tenant = Tenant::get($businessId);
        if($tenant->wxStatus != 0){
            $tenant->wxStatus = 0;
            $tenant->auditid = 0;
            $tenant->appId = null;
            $tenant->authorizerAccessToken = null;
            $tenant->authorizerRefreshToken = null;
            if($tenant->save()){
                return show(config('status.SUCCESS_STATUS'),"解绑成功",'解绑成功');
            }

        }else{
            return show(config('status.ERROR_STATUS'),'当前无法解绑','当前无法解绑');
        }
    }

    public function addexperiencer(Request $request){
        $businessId = session('TENANT_ID');
        $param = $request->param();
        if(!$param['wechat_id']){
            return show(config('status.ERROR_STATUS'),'请求参数异常');
        }

        $res = MiniProgramHelp::AddWechatExperiencer($businessId,$param['wechat_id']);
        if($res['errcode'] != 0){
            if($res['errcode'] == 85001){
                return show(config('status.ERROR_STATUS'),'微信号不存在或微信号设置为不可搜索','微信号不存在或微信号设置为不可搜索');
            }elseif ($res['errcode'] == 85002){
                return show(config('status.ERROR_STATUS'),'小程序绑定的体验者数量达到上限','小程序绑定的体验者数量达到上限');
            }elseif ($res['errcode'] == 85003){
                return show(config('status.ERROR_STATUS'),'微信号绑定的小程序体验者达到上限','微信号绑定的小程序体验者达到上限');
            }elseif ($res['errcode'] == 85004){
                return show(config('status.ERROR_STATUS'),'微信号已经绑定','微信号已经绑定');
            }else{
                return show(config('status.ERROR_STATUS'),'系统繁忙','系统繁忙');
            }
        }else{
            return show(config('status.SUCCESS_STATUS'),'绑定成功','绑定成功');
        }
    }



}